<template>
  <el-config-provider :locale="zhCn">
    <el-scrollbar>
      <div :class="{ hidden: hidden }" class="material-pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :background="background"
          :layout="layout"
          :page-sizes="pageSizes"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-scrollbar>
  </el-config-provider>
</template>

<script setup lang="ts">
import { watch, type PropType } from 'vue'
import { defineProps, defineEmits, defineModel } from 'vue'
import { ElScrollbar, ElPagination, ElConfigProvider } from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn'

const props = defineProps({
  total: {
    required: true,
    type: Number,
    default: 0,
  },
  pageSizes: {
    type: Array as PropType<number[]>,
    default() {
      return [10, 30, 50, 100, 500, 2000]
    },
  },
  layout: {
    type: String,
    default: 'total, sizes, prev, pager, next, jumper',
  },
  background: {
    type: Boolean,
    default: true,
  },
  autoScroll: {
    type: Boolean,
    default: true,
  },
  hidden: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(['pagination'])

const currentPage = defineModel('page', {
  type: Number,
  required: true,
  default: 1,
})
const pageSize = defineModel('pageSize', {
  type: Number,
  required: true,
  default: 10,
})

watch(
  () => props.total,
  (newVal: number) => {
    const lastPage = Math.ceil(newVal / pageSize.value)
    if (newVal > 0 && currentPage.value > lastPage) {
      currentPage.value = lastPage
      emit('pagination', { page: currentPage.value, pageSize: pageSize.value })
    }
  }
)

function handleSizeChange(val: number) {
  currentPage.value = 1
  emit('pagination', { page: currentPage.value, pageSize: val })
}

function handleCurrentChange(val: number) {
  emit('pagination', { page: val, pageSize: pageSize.value })
}
</script>

<style lang="scss" scoped>
.material-pagination {
  padding: 12px;

  &.hidden {
    display: none;
  }

  :deep(.el-pagination) {
    justify-content: center;
  }
}
</style>